package com.Txunda.fxw.ui.fgt;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.Txunda.fxw.R;
import com.Txunda.fxw.base.utils.util.JSONUtils;
import com.Txunda.fxw.base.utils.util.L;
import com.Txunda.fxw.base.utils.util.ListUtils;
import com.Txunda.fxw.base.utils.util.MapUtils;
import com.Txunda.fxw.ui.adapter.LawMyAdp;
import com.Txunda.fxw.ui.adapter.model.SummaryModel;
import com.Txunda.fxw.ui.base.BaseFgt;
import com.Txunda.fxw.ui.http.Company;
import com.Txunda.fxw.ui.http.Office;
import com.Txunda.fxw.ui.toolkit.util.DensityUtil;
import com.Txunda.fxw.ui.toolkit.util.PreferenceUtil;
import com.Txunda.fxw.ui.widget.XCSlideView;
import com.Txunda.fxw.view.RoundedImageView;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class Law2Fgt extends BaseFgt {
    @ViewInject(R.id.aty_title3_icon)
    private ImageView aty_title3_icon;

    @ViewInject(R.id.aty_title3_tv_center)
    private TextView aty_title3_tv_center;
    @ViewInject(R.id.aty_title3_tv_right2)
    private TextView aty_title3_tv_right2;
    @ViewInject(R.id.icon_logo)
    private RoundedImageView icon_logo;

    @ViewInject(R.id.lv_LawServiceAty)
    private ListView lv_LawServiceAty;

    private XCSlideView mSlideViewRight;
    private ListView area_lv;
    private Bundle bundle;
    private String class_id;

    private TextView tv_count; // 全部商圈总数
    private Company company;
    private My2Adapter adapter;
    /**
     * 地区id
     */
    private String district_id = "";
    /**
     * 省id
     */
    private String province_id = "";
    /**
     * 城市id
     */
    private String city_id = "";
    private String lat = "";
    private String lnt = "";
    private ArrayList<Map<String, String>> company_list_data = new ArrayList<>();
    private ArrayList<SummaryModel> cityList = new ArrayList<>();
    private ArrayList<SummaryModel> districtList = new ArrayList<>();

    protected int index;
    private String districtName;
    private int dataType = 0;
    protected String cityName = "";
    private Office office;
    private LawMyAdp adp;
    private List<SummaryModel> list_data2;
    public Context me;

    public Law2Fgt() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fgt_law2;
    }

    @Override
    protected void initialized() {
        office = new Office();
        company = new Company();
        list_data2 = new ArrayList<>();
        // 侧滑
        Context mContext = getActivity();
        // 屏幕宽度
        int mScreenWidth = DensityUtil.getScreenWidthAndHeight(mContext)[0];
        mSlideViewRight = XCSlideView.create(getContext(), XCSlideView.Positon.RIGHT);
        View menuViewRight = LayoutInflater.from(mContext).inflate(R.layout.layout_area, null);
        mSlideViewRight.setMenuView(getContext(), menuViewRight);
        tv_count = menuViewRight.findViewById(R.id.tv_count);
        mSlideViewRight.setMenuWidth(mScreenWidth * 6 / 9);

        area_lv = menuViewRight.findViewById(R.id.area_list);

    }

    @Override
    protected void requestData() {

        aty_title3_icon.setVisibility(View.GONE);
        aty_title3_tv_center.setText("茶邦联盟");
        String logo = PreferenceUtil.readString(getActivity(), PreferenceUtil.sp_logo);
        Glide.with(getActivity()).load(logo).into(icon_logo);
        String area_name = PreferenceUtil.readString(getActivity().getApplicationContext(), PreferenceUtil.sp_mode);
        aty_title3_tv_right2.setVisibility(View.VISIBLE);
        aty_title3_tv_right2.setText(area_name);
        showProgressDialog();
        office.lawList(this);
        showProgressDialog();
        //数据请求
        office.preservationlist(null, "0", null, this);
        lv_LawServiceAty.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (adp == null) {
                    return;
                }
                Map<String, String> item = adp.getItem(position);
                Bundle bundle = new Bundle();
                bundle.putString("type", "fb");
                bundle.putString("class_id", item.get("id"));
                bundle.putString("count", "1");
                bundle.putString("com_id", item.get("id"));
                bundle.putString("url", item.get("url"));
                startActivity(WebAty.class, bundle);
            }
        });

        icon_logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mSlideViewRight.isShow()) {
                    mSlideViewRight.show();
                }
                showProgressDialog();
                office.summary(Law2Fgt.this);
            }
        });
    }

    private ArrayList<Map<String, String>> dataPreservationlist = new ArrayList<>();

    @Override
    public void onComplete(String requestUrl, String jsonStr) {
        super.onComplete(requestUrl, jsonStr);
        removeProgressDialog();
        removeProgressContent();
        Log.d("zdl", "===========省级地区==============: " + requestUrl);
        if (requestUrl.contains("preservationlist")) {
            dataPreservationlist.clear();
            if (adp != null) {
                adp.notifyDataSetChanged();
            }

            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            Log.d("zdl", "===========preservationlist==============: " + map.toString());
            if (MapUtils.isEmpty(map)) {
                return;
            }
            ArrayList<Map<String, String>> data = JSONUtils.parseKeyAndValueToMapList(map.get("data"));
            if (data == null) {
                return;
            }
            dataPreservationlist.addAll(data);
            adp = new LawMyAdp(getContext(), dataPreservationlist);
            lv_LawServiceAty.setAdapter(adp);
        }
        getSummary(requestUrl, jsonStr);// 省
        getSummaryCity(requestUrl, jsonStr);// 市
        getSummaryDistrict(requestUrl, jsonStr);// 地区

    }

    @Override
    public void onError(String requestUrl, Map<String, String> error) {
//        company_list_lv.onRefreshComplete();
        removeProgressDialog();
        removeProgressContent();
        try {
            districtName = cityList.get(index).getName();
            showToast("已切换至" + districtName);
            aty_title3_tv_right2.setText(districtName);
            adapter.notifyDataSetChanged();
            /*
             * 地区id
             */
            showProgressDialog();
            //数据请求
            getCompanyList();
            if (mSlideViewRight.isShow()) {
                mSlideViewRight.dismiss();
            }
        } catch (Exception e) {
            L.e(e.getMessage());
        }
    }

    public void getCompanyList() {
//        地址筛选传地区的id   area_id
//    0默认传城市，1传地区   type   name
//            这个默认进来还是传地区名称，筛选三亚的话type传0然后name传三亚
//        office.preservationlist(districtName, "1", city_id, this);
        Log.d("zdl","========district_id========="+district_id);
        Log.d("zdl","========districtName========="+districtName);
        office.preservationlist(district_id, "1", districtName, this);
//        company.companyList(lat, lnt, p, class_id, district_id, city_id, province_id, this);
    }

    /**
     * 地区筛选adapter
     *
     * @author Administrator
     */
    public class My2Adapter extends BaseAdapter {

        List<SummaryModel> list;
        My2Adapter.MyViewHolder vh;

        public My2Adapter(List<SummaryModel> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            int ret = 0;
            if (list != null) {
                ret = list.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_area_lv, parent, false);
                vh = new My2Adapter.MyViewHolder();
                ViewUtils.inject(vh, convertView);
                convertView.setTag(vh);
            } else {
                vh = (My2Adapter.MyViewHolder) convertView.getTag();
            }
            Log.d("zdl", "========获取到的数据=========" + list.get(position).getName());
            Log.d("zdl", "========获取到的数据=========" + list.get(position).getCount());
            vh.item_area_name.setText(list.get(position).getName()); // 地区名称
            vh.item_area_num.setText(list.get(position).getCount()); // 数量

            return convertView;
        }

        class MyViewHolder {
            @ViewInject(R.id.item_area_name)
            private TextView item_area_name;
            @ViewInject(R.id.item_area_num)
            private TextView item_area_num;
        }
    }

    /**
     * 区
     */
    private void getSummaryDistrict(String requestUrl, String jsonStr) {

        if (requestUrl.contains("summaryDistrict")) { // 地区
            Log.d("zdl", "===========地区==============: " + requestUrl);
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if (MapUtils.isEmpty(map)) {
                return;
            }
            if ("success".equals(map.get("flag"))) {
                districtList.clear();
                Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                if (MapUtils.isEmpty(data)) {
                    return;
                }
                data.get("count");
                List<Map<String, String>> tempList = JSONUtils.parseKeyAndValueToMapList(data.get("list"));
                if (!ListUtils.isEmpty(tempList)) {

                    for (Map<String, String> temp : tempList) {
                        districtList
                                .add(new SummaryModel(temp.get("city_name"), temp.get("district_id"), temp.get("c_count")));
                    }
                    adapter = new My2Adapter(districtList);
                    area_lv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    area_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // 地区id
                            districtName = districtList.get(position).getName();
                            showToast("已切换至" + districtName);
                            aty_title3_tv_right2.setText(cityName);
                            adapter.notifyDataSetChanged();

                            district_id = districtList.get(position).getId();
                            // 刷新商家列表数据
                            showProgressDialog();
                            //数据请求
                            getCompanyList();

                            if (mSlideViewRight.isShow()) {
                                mSlideViewRight.dismiss();
                            }
                        }
                    });
                }

            }
        }
    }

    /**
     * 市
     */
    private void getSummaryCity(String requestUrl, String jsonStr) {
        if (requestUrl.contains("summaryCity")) { // 市级
            Log.d("zdl", "===========市级地区====342==========: " + requestUrl);
            Log.d("zdl", "===========市级地区=====343=========: " + jsonStr);
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            Log.d("zdl", "===========市级地区=====345=========: " + map.toString());
            if ("success".equals(map.get("flag"))) {
                Log.d("zdl", "===========市级地区=====347=========: " + map.get("flag"));
                cityList.clear();
                Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                Log.d("zdl", "===========市级地区=====data=438========: " + data.toString());

                String count = data.get("count");
                tv_count.setText(count);
                ArrayList<Map<String, String>> list = JSONUtils.parseKeyAndValueToMapList(data.get("list"));
                Log.d("zdl", "===========市级地区=====list===353======: " + list.toString());
                Log.d("zdl", "=======集合总数=======" + list.size());
                for (Map<String, String> listadd : list) {
                    Log.d("zdl", "=======集合总数====city_name===" + listadd.get("city_name").toString().trim());
                    cityList.add(new SummaryModel(listadd.get("city_name"), listadd.get("city_id"), listadd.get("c_count")));
                }

                adapter = new My2Adapter(cityList);
                area_lv.setAdapter(adapter);
                // 获取商家列表
                area_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // 回传district_id
                        city_id = cityList.get(position).getId(); // id

                        Log.d("zdl", "==========id=========== " + city_id);
                        // 获取区县列表
                        showProgressDialog();
                        office.summaryDistrict(city_id, Law2Fgt.this);

                        index = position;
                        adapter.notifyDataSetChanged();
                        // 保存本地数据
                        cityName = cityList.get(position).getName();
                        PreferenceUtil.write(getContext(), PreferenceUtil.sp_mode, cityName);

                        aty_title3_tv_right2.setText(cityList.get(position).getName());
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }
    }

    /**
     * 省
     */
    private void getSummary(String requestUrl, String jsonStr) {
        if (requestUrl.contains("summary")) { // 省级地区
            Log.d("zdl", "===========省级地区==============: " + jsonStr);
            Map<String, String> map = JSONUtils.parseKeyAndValueToMap(jsonStr);
            if ("success".equals(map.get("flag"))) {
                list_data2.clear();
                final Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                String count = data.get("count"); // 全部商圈总数
                tv_count.setText(count);
                for (Map<String, String> temp : JSONUtils.parseKeyAndValueToMapList(data.get("list"))) {
                    list_data2.add(new SummaryModel(temp.get("province_name"), temp.get("province_id"), temp.get("c_count")));
                }

                adapter = new My2Adapter(list_data2);
                area_lv.setAdapter(adapter);
                area_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        province_id = list_data2.get(position).getId(); // 地区id
                        showProgressDialog();
                        office.summaryCity(province_id, Law2Fgt.this); // 省集合
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }
    }
}
